Paint fence¶
Time: O(N); Space: O(1); easy
There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
Constraints:
n and k are non-negative integers.
Example 1:
Input: n=3, k=2
Output: 6
Explanation:
post 1, post 2, post 3
way1 0 0 1
way2 0 1 0
way3 0 1 1
way4 1 0 0
way5 1 0 1
way6 1 1 0
Example 2:
Input: n=2, k=2
Output: 4
Explanation:
post 1, post 2
way1 0 0
way2 0 1
way3 1 0
way4 1 1
1. Dynamic Programming¶
[1]:
class Solution1(object):
"""
Time: O(N)
Space: O(1)
"""
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return k
ways = [0] * 3
ways[0] = k
ways[1] = (k - 1) * ways[0] + k
for i in range(2, n):
ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3])
return ways[(n - 1) % 3]
[2]:
s = Solution1()
n=3
k=2
assert s.numWays(n, k) == 6
n = 2
k = 2
assert s.numWays(n, k) == 4
2. Dynamic Programming¶
[4]:
class Solution2(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return k
ways = [0] * n
ways[0] = k
ways[1] = (k - 1) * ways[0] + k
for i in range(2, n):
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2])
return ways[n - 1]
[5]:
s = Solution2()
n=3
k=2
assert s.numWays(n, k) == 6
n = 2
k = 2
assert s.numWays(n, k) == 4